/*
 * The MIT License (MIT)
 *
 * Copyright (c) 2016 pjoc.pub, blademainer.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 *
 */

package pub.pjoc.pay.threadpool.asynchronous.impl;

import pub.pjoc.pay.threadpool.asynchronous.AsynchronousInvokerService;
import pub.pjoc.pay.threadpool.asynchronous.FutureMonitor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.*;

/**
 * Default asynchronous invoker.
 *
 * @author blademainer
 * @version 2016-08-31 23:16
 */
public class AsynchronousInvokerServiceImpl implements AsynchronousInvokerService {
  private static final Logger logger = LoggerFactory
      .getLogger(AsynchronousInvokerServiceImpl.class);

  private ThreadPoolExecutor executorService = new ThreadPoolExecutor(10, 10, 0L,
      TimeUnit.MILLISECONDS,
      new LinkedBlockingQueue<Runnable>());
  private BlockingQueue<FutureMonitor<Boolean>> futureBlockingQueue = new LinkedBlockingQueue<FutureMonitor<Boolean>>();

  @Override
  public boolean submit(Callable<Boolean> callable) {
    Future<Boolean> submit = executorService.submit(callable);
    FutureMonitor<Boolean> futureMonitor = new FutureMonitor<Boolean>();
    futureMonitor.setCallable(callable);
    futureMonitor.setFuture(submit);
    boolean added = futureBlockingQueue.add(futureMonitor);
    if (added) {
      if (logger.isDebugEnabled()) {
        logger.debug(
            "Submitted a callable to thread pool! callable: {} thread pool status: {}",
            callable, executorService);
      }
    } else {
      logger.error("Submit callable: {} to thread pool error! Thread pool status: {}",
          callable, executorService);
    }
    return added;
  }

  @Override
  public BlockingQueue<FutureMonitor<Boolean>> futureBlockingQueue() {
    return futureBlockingQueue;
  }

  @Override
  public ThreadPoolExecutor getThreadPool() {
    return executorService;
  }


}
